package com.lh.servlet.server02;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletInputStream;

import org.apache.naming.StringManager;

public class RequestStreamLh02 extends ServletInputStream {

	// ------------------------------------------------------- Instance
	// Variables

	/**
	 * had the stream been closed
	 */
	protected boolean closed = false;

	/**
	 * the number of bytes which have already been returned by this stream
	 */
	protected int count = 0;

	/**
	 * the content length past which we will not read,or -1 if there is no
	 * defined content length
	 */
	protected int length = -1;

	protected static StringManager sm = StringManager
			.getManager(ConstantsLh02.class.getPackage().getName());

	/**
	 * The underlying input stream from which we should read data
	 */
	protected InputStream stream = null;

	// ---------------------------------------------------------- Constructor

	/**
	 * Constuct a servlet input stream associated with the specified request
	 */
	public RequestStreamLh02(HttpRequestLh02 request) {
		super();
		closed = false;
		count = 0;
		length = request.getContentLength();
		stream = request.getStream();

	}

	// -------------------------------------------------method
	public void close() throws IOException {

		if (closed)
			throw new IOException(sm.getString("requestStream.close.closed"));

		if (length > 0) {
			while (count < length) {
				int b = read();
				if (b < 0)
					break;
			}
		}
		closed = true;
	}

	public int read() throws IOException {
		// has this stream been closed?
		if (closed)
			throw new IOException(sm.getString("requestStream.read.closed"));

		// have we read the specified content length already
		if ((length >= 0) && (count >= length)) {
			return (-1); // end of file indicator
		}

		// read and count the next byte,then return it
		int b = stream.read();
		if (b >= 0)
			count++;

		return (b);
	}

	public int read(byte[] bytes) throws IOException {
		return read(bytes, 0, bytes.length);
	}

	public int read(byte[] b, int off, int len) throws IOException {

		int toRead = len;
		if (length > 0) {
			if (count >= length)
				return (-1);
			if ((count + len) > length)
				toRead = length - count;
		}

		int actuallyRead = super.read(b, off, toRead);

		return (actuallyRead);

	}

}
